package com.llh.cheap.services;

import com.llh.cheap.models.CheapUser;
import com.llh.cheap.forms.CheapUserForm;
import com.llh.cheap.repositories.CheapUserRepository;
import org.springframework.transaction.support.TransactionTemplate;
import top.moirae.repository.PaginationData;
import top.moirae.repository.PaginationForm;
import top.moirae.security.forms.IdsForm;
import top.moirae.core.AbstractEither;
import top.moirae.core.ErrorMessage;
import top.moirae.core.Right;
import jakarta.inject.Inject;
import jakarta.inject.Named;

import java.util.Arrays;
import java.util.List;

/**
 * @author lilinhan
 **/
@Named
public class CheapUserService {
    private final CheapUserRepository cheapUserRepository;
    private final TransactionTemplate transactionTemplate;

    @Inject
    public CheapUserService(CheapUserRepository cheapUserRepository, @Named("BUSINESS_TT") TransactionTemplate transactionTemplate) {
        this.cheapUserRepository = cheapUserRepository;
        this.transactionTemplate = transactionTemplate;
    }

    public AbstractEither<ErrorMessage, Long> create(long optUserId, CheapUserForm.Create form) {
        return Right.apply(cheapUserRepository.create(form));
    }

    public AbstractEither<ErrorMessage, CheapUser> get(Long id) {
        return cheapUserRepository.option(id).toRight(CheapUser.Errors.NOT_FOUND);
    }

    public AbstractEither<ErrorMessage, Long> update(long optUserId, long id, CheapUserForm.Update form) {
        return Right.apply(cheapUserRepository.update(id, form));
    }

    public AbstractEither<ErrorMessage, Integer> delete(IdsForm ids) {
        return transactionTemplate.execute(status -> Right.apply(Arrays.stream(ids.getIds()).mapToInt(cheapUserRepository::delete).sum()));
    }

    public AbstractEither<ErrorMessage, Boolean> isExist(long id) {
        return Right.apply(cheapUserRepository.isExist(id));
    }

    public AbstractEither<ErrorMessage, List<CheapUser>> list(CheapUserForm.Search form) {
        return Right.apply(cheapUserRepository.list(form));
    }

    public AbstractEither<ErrorMessage, PaginationData<CheapUser>> pageList(CheapUserForm.Search form, PaginationForm paginationForm) {
        return Right.apply(cheapUserRepository.pageList(form, paginationForm));
    }
}

